// pages/publish/publis.js
const app = getApp()
Page({
  onShow: function(){
    if(app.globalData.userInfo.qrCode == null){
      wx.navigateTo({
        url: '/pages/code/code',
      })
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    imageList: [],
    category: [
      "书籍",
      "体育娱乐",
      "美妆护肤",
      "生活用品",
      "衣物",
      "其他"
    ],
    categoryIndex: null,
    price: null,
    discount: false,
    title: "",
    desc: ""
  },

  categoryMapping(value) {
    switch (value) {
      case '书籍':
        return 'BOOK';
      case '体育娱乐':
        return 'SPORT';
      case '生活用品':
        return 'DAILY';
      case '美妆护肤':
        return 'COSMETICS';
      case '衣物':
        return 'CLOTHES';
      case '其他':
        return 'OTHER';
    }
  },

  changeData: function(e) {
    let name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },

  pickerChange: function(e) {
    this.setData({
      categoryIndex: e.detail.value
    })
  },

  chooseImage: function() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        for (let i of res.tempFiles) {
          // 1024 * 1024 * 4
          if (i.size > 4194304) {
            wx.showToast({
              title: '图片超出大小限制（4MB）',
              icon: 'none'
            })
            return;
          }
        }

        if (this.data.imageList.length != 0) {
          this.setData({
            imageList: this.data.imageList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imageList: res.tempFilePaths
          })
        }


      }
    });
  },

  viewImage: function(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },

  delImg(e) {
    this.data.imageList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imageList: this.data.imageList
    })
  },

  publish() {
    if (this.checkRequire() == false) {
      return;
    }
    let self = this
    let host = getApp().globalData.host
    let imageList = this.data.imageList;
    let hostImages = [];

    // 先把图片一张张发送到后台, 图片url最终存储在 hostImages 中
    hostImages = self.uploadImgae(host, imageList, 0, hostImages)
    
  },

  /**
  * 上传图片
  */
  uploadImgae(host, sourceImages, index, hostImages) {
    let self = this

    wx.uploadFile({
      url: host + '/item/image',
      filePath: sourceImages[index],
      name: 'image',
      success: function (res) {
        let result = JSON.parse(res.data)
        hostImages.push(result.data)
        index++;
        if(index >= sourceImages.length){
          console.log("index"+ index)
          console.log("hostImages"+ hostImages)
          self.uploadAll(hostImages)
        }
        self.uploadImgae(host, sourceImages, index, hostImages)
      },
      error: function () {
        console.error('image upload error')
        wx.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 上传总的
   */
  uploadAll(hostImages){
    let self = this
    let category = this.categoryMapping(self.data.category[self.data.categoryIndex])
    let host = getApp().globalData.host
    let token = wx.getStorageSync('token');
    
    wx.request({
      url: host + '/item',
      method: "POST",
      header: {
        'authorization': token
      },
      data: {
        category: category,
        title: self.data.title,
        description: self.data.desc,
        images: JSON.stringify(hostImages),
        price: self.data.price,
        discount: self.data.discount
      },
      success: function (res) {
        console.log(res)
        wx.showToast({
          title: '发布成功',
          duration: 3000
        })
      }
    })
  },

  /*
   * 检查必填项
   */
  checkRequire() {
    let title = this.data.title
    let images = this.data.imageList
    let categoryIndex = this.data.category
    let price = this.data.price
    if (title == null || categoryIndex == null || price < 0.0 || images.length == 0) {
      wx.showToast({
        title: '必填项不能为空或非法值',
        icon: 'none'
      })
      return false
    }
    return true
  },


  moneyInput(e) {
    var price;
    if (/[1-9]+[0]*/.test(e.detail.value)) { //正则验证，提现金额小数点后不能大于两位数字
      price = e.detail.value;
    } else {
      price = e.detail.value.substring(0, e.detail.value.length - 1);
    }
    this.setData({
      price: price,
    })
  }
})